# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : mapReduce聚合操作2.py
# @Author: dongguangwen
# @Date  : 2025-06-15 17:05
# pip install pymongo==3.12.3  4.0+版本不支持
from pymongo import MongoClient

client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')
db = client['learning_mongodb']
collection = db['users']


# Map 函数：为每个用户的成绩发射 (name, {sum: score, count: 1})
mapper = """
function () {
    this.scores.forEach(function(score) {
        emit(this.name, { sum: score, count: 1 });
    }, this);
}
"""

# Reduce 函数：合并同一用户的多个记录
reducer = """
function (key, values) {
    var total = { sum: 0, count: 0 };
    values.forEach(function(value) {
        total.sum += value.sum;
        total.count += value.count;
    });
    return total;
}
"""

# Finalize 函数：计算平均值
finalize = """
function (key, reducedValue) {
    if (reducedValue.count == 0) return 0;
    return reducedValue.sum / reducedValue.count;
}
"""

# 执行 MapReduce
result = collection.map_reduce(
    mapper,
    reducer,
    out="user_avg_score",
    finalize=finalize
)

# 查询输出结果
print("每位用户的平均成绩：")
for doc in result.find():
    print(f"{doc['_id']}: {round(doc['value'], 2)}")

"""
每位用户的平均成绩：
User_3: 80.04
User_4: 85.88
User_5: 75.68
User_10: 78.92
User_7: 80.3
User_2: 82.2
User_8: 70.64
User_6: 75.28
User_9: 85.08
User_1: 87.64
"""
